import { getName } from '@tauri-apps/api/app';
import { invoke } from '@tauri-apps/api/core';
import { Menu } from '@tauri-apps/api/menu';
import { resolveResource } from '@tauri-apps/api/path';
import { TrayIcon, TrayIconOptions } from '@tauri-apps/api/tray';

export default class SystemTray {
  private static systemTray: TrayIcon | null;

  public static async getTrayWithMenu(menuTextObj: { exitText: string }): Promise<TrayIcon> {
    await this.updateMenu(menuTextObj);
    return this.systemTray!;
  }

  public static async updateMenu(menuTextObj: { exitText: string }): Promise<void> {
    const menu = await this.createMenu(menuTextObj);
    const instance = await this.getInstance();
    instance.setMenu(menu);
  }

  private static async getInstance(): Promise<TrayIcon> {
    if (!this.systemTray) {
      const tooltip = await getName();

      // MUST use resolveResource for both dev and release.
      const iconPath = await resolveResource('icons/tray-icon.png');

      const options: TrayIconOptions = {
        tooltip: tooltip,
        icon: iconPath,
        menuOnLeftClick: false,
      };

      this.systemTray = await TrayIcon.new(options);
    }

    return this.systemTray;
  }

  private static async createMenu(menuTextObj: { exitText: string }): Promise<Menu> {
    return Menu.new({
      items: [
        {
          id: 'exit',
          text: menuTextObj.exitText,
          action: () => invoke('exit_app'),
        },
      ],
    });
  }
}
